#include "GUIPch.h"

#include "GUIManager.h"
#include "XmlUtil.h"

#include "GUIButton.h"
#include "GUIImage.h"
#include "GUIText.h"

GUIManager::GUIManager()
{

}

GUIManager::~GUIManager()
{
	int guiCount = (int)m_guiList.size();
	for( int cnt = 0; cnt < guiCount; cnt++ )
	{
		if( m_guiList[cnt] )
		{
			SAFE_DELETE( m_guiList[cnt] );
		}
	}
}

void GUIManager::Init()
{
}

void GUIManager::UnInit()
{
	Release();
}

BOOL GUIManager::LoadGUIList( std::string xmlFileName )
{
	XmlDocument doc;
	if( doc.LoadFile( xmlFileName.c_str() ) )
	{
		XmlNode * guiListNode = doc.GetChildNode( "gui_list" );

		int guiNodeCount = guiListNode->GetChildNodeCount( "gui" );
		for( int cnt = 0; cnt < guiNodeCount; cnt++ )
		{
			XmlNode * guiNode = guiListNode->GetChildNode( "gui", cnt );
			std::string guiType = guiNode->GetAttribute( "type" );

			GUIBase * gui = NULL;

			if( guiType == "text" )
			{
				gui = new GUIText();
			}
			else if( guiType == "image" )
			{
				gui = new GUIImage();
			}
			else if( guiType == "button" )
			{
				gui = new GUIButton();
			}

			if( gui->LoadFromXML( guiNode ) )
			{
				m_guiList.push_back( gui );
			}
			else
			{
				SAFE_DELETE( gui );
			}
		}

		return TRUE;
	}

	return FALSE;
}

void GUIManager::Update( float fTimeDelta )
{
	int guiCount = (int)m_guiList.size();
	for( int cnt = 0; cnt < guiCount; cnt++ )
	{
		if( m_guiList[cnt] )
		{
			m_guiList[cnt]->Update( fTimeDelta );
		}
	}
}

void GUIManager::Render()
{	
	int guiCount = (int)m_guiList.size();
	for( int cnt = 0; cnt < guiCount; cnt++ )
	{
		if( m_guiList[cnt] )
		{
			m_guiList[cnt]->Render();
		}
	}
}

GUIBase * GUIManager::GetGUIByID( const std::string id )
{
	GUIBase * result = NULL;

	int guiCount = (int)m_guiList.size();
	for( int cnt = 0; cnt < guiCount; cnt++ )
	{
		if( m_guiList[cnt]->GetID() == id )
		{
			result = m_guiList[cnt];
			break;
		}
	}

	return result;
}

BOOL GUIManager::PopGUIMessage( GUIMessage & msg )
{
	if( m_guiMessageDeque.empty() == false )
	{
		msg = m_guiMessageDeque.front();	
		m_guiMessageDeque.pop();	

		return TRUE;
	}

	return FALSE;
}

void GUIManager::HandleEvent( UINT message, WPARAM wParam, LPARAM lParam )
{
	int guiCount = (int)m_guiList.size();
	for( int cnt = 0; cnt < guiCount; cnt++ )
	{
		if( m_guiList[cnt] )
		{
			if( m_guiList[cnt]->HandleEvent( message, wParam, lParam ) )
			{
				GUIMessage guiMessage;
				guiMessage.m_guiID = m_guiList[cnt]->GetID();
				guiMessage.m_message = message;

				m_guiMessageDeque.push( guiMessage );
			}
		}
	}
}